const Eos = require('eosjs')
const ecc = require('eosjs-ecc');

const eossuperdice = 'luckydicewin';
const wif  ='5HuBWbyZz2gzrrejd7LYm4ukRWaGKVQD9o74dExspNgS88HHWNQ';  //部署合约的账号签名
const config = {
    chainId: 'aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906', // 32 byte (64 char) hex string
    keyProvider: ['5HuBWbyZz2gzrrejd7LYm4ukRWaGKVQD9o74dExspNgS88HHWNQ'], // 合约执行者的 WIF string or array of keys..
    httpEndpoint: 'http://mainnet.eoscannon.io',
    expireInSeconds: 60,
    broadcast: true,
    verbose: false, // API activity
    sign: true,
    authorization:[{
      actor: 'luckydiceman',
      permission: 'active'
      }    
    ]
}
const eos = Eos(config);
async function open_bet(contract,id,random_seed) {
   return contract.reveal(id, random_seed);
}

var flag = false;
var index = 0;
async function open_contract(contract) {
    console.log('open_contract start')
    let result = await  eos.getTableRows(true, eossuperdice, eossuperdice, 'bets', 
 eossuperdice, 0, -1, 10, "", "");
            console.log('open_contract getTableRows success ')
            let rows = result.rows
            console.log('bets rows=>'+rows);
            let len = rows.length
            console.log('bets length=>'+len);

            for(let i = 0; i < len; i ++) {
                var id = result.rows[i].id
                var player = result.rows[i].player
                var referrer = result.rows[i].referrer
                var amount = result.rows[i].amount
                var roll_under = result.rows[i].roll_under
                var seed_hash = result.rows[i].seed_hash
                var user_seed_hash = result.rows[i].seed_hash
                var created_at = result.rows[i].seed_hash
                let random_seed  = Math.random().toString(36).substr(2)+Date.now();
                random_seed = ecc.sha256(random_seed);
                console.log('ready to invoke contract ,id='+id+',random_seed='+random_seed);
                open_bet(contract, id, random_seed);
            }
            flag = true;
}

//调用合约
eos.contract(eossuperdice).then((contract) => {
    console.log('invoke contract:eossuperdice  success ,time=>'+Date.now());
    open_contract(contract);
    setInterval(function() {
        console.log('interval index=>'+index);
        if( flag ){
            index++;
            if(index > 65535) {
                index = 0;
            }
            open_contract(contract);
        }
    },1000);
}).catch((err)=> {
    console.log('error:',err);
});



